package com.example.SearchAround_JC.jc_activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.*;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.*;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.navi.BaiduMapNavigation;
import com.baidu.mapapi.navi.NaviPara;
import com.baidu.mapapi.overlayutil.DrivingRouteOverlay;
import com.baidu.mapapi.overlayutil.OverlayManager;
import com.baidu.mapapi.overlayutil.TransitRouteOverlay;
import com.baidu.mapapi.overlayutil.WalkingRouteOverlay;
import com.baidu.mapapi.search.core.RouteLine;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.route.*;
import com.example.SearchAround_JC.R;
import com.example.SearchAround_JC.jc_manager.Distance;

/**
 * Created by Administrator on 2014/11/25.
 */
public class POIdetails_Activity extends Activity {
    private TabHost tabhost;
    private Button poi_details_back_bt;
    private TextView poidetails_name_TextView;
    private TextView poidetails_address_TextView;
    private TextView poidetails_phone_TextView;
    private TextView detail_distance_TextView;
    private Button poi_details_rote_Bt;
    LatLng fromLatLng;
    LatLng toLatLng;
    int nodeIndex = -1;//节点索引,供浏览节点时使用
    RouteLine route = null;
    OverlayManager routeOverlay = null;
    boolean useDefaultIcon = false;
    private TextView popupText = null;//泡泡view

    //地图相关，使用继承MapView的MyRouteMapView目的是重写touch事件实现泡泡处理
    //如果不处理touch事件，则无需继承，直接使用MapView即可
    MapView mMapView = null;    // 地图View
    BaiduMap mBaidumap = null;
    //搜索相关
    RoutePlanSearch mSearch = null;    // 搜索模块，也可去掉地图模块独立使用

    //定位图层
    LocationClient locationClient;
    private MyLocationConfiguration.LocationMode mCurrentMode;
    BitmapDescriptor mCurrentMarker;
    boolean isFirstLoc = true;// 是否首次定位
    public MyLocationListenner myListener = new MyLocationListenner();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_poi_details);


        //初始化地图
        mMapView = (MapView) findViewById(R.id.details_mapView);
        mMapView.showZoomControls(false);
        mBaidumap = mMapView.getMap();
        mBaidumap.setMapStatus(MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder().zoom(10).build()));
        mBaidumap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {

            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        });

        poi_details_rote_Bt = (Button) findViewById(R.id.poi_details_rote_bt);
        poi_details_rote_Bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startWebNavi(fromLatLng,toLatLng);
            }
        });

        mSearch = RoutePlanSearch.newInstance();
        mSearch.setOnGetRoutePlanResultListener(new OnGetRoutePlanResultListener() {
            @Override
            public void onGetWalkingRouteResult(WalkingRouteResult result) {
                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    Toast.makeText(POIdetails_Activity.this, "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
                }
                if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
                    //起终点或途经点地址有岐义，通过以下接口获取建议查询信息
                    //result.getSuggestAddrInfo()
                    return;
                }
                if (result.error == SearchResult.ERRORNO.NO_ERROR) {
                    nodeIndex = -1;
                    route = result.getRouteLines().get(0);
                    WalkingRouteOverlay overlay = new MyWalkingRouteOverlay(mBaidumap);
                    mBaidumap.setOnMarkerClickListener(overlay);
                    routeOverlay = overlay;
                    overlay.setData(result.getRouteLines().get(0));
                    overlay.addToMap();
                    overlay.zoomToSpan();
                }
            }

            @Override
            public void onGetTransitRouteResult(TransitRouteResult result) {
                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    Toast.makeText(POIdetails_Activity.this, "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
                }
                if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
                    //起终点或途经点地址有岐义，通过以下接口获取建议查询信息
                    //result.getSuggestAddrInfo()
                    return;
                }
                if (result.error == SearchResult.ERRORNO.NO_ERROR) {
                    nodeIndex = -1;
                    route = result.getRouteLines().get(0);
                    TransitRouteOverlay overlay = new MyTransitRouteOverlay(mBaidumap);
                    mBaidumap.setOnMarkerClickListener(overlay);
                    routeOverlay = overlay;
                    overlay.setData(result.getRouteLines().get(0));
                    overlay.addToMap();
                    overlay.zoomToSpan();
                }
            }

            @Override
            public void onGetDrivingRouteResult(DrivingRouteResult result) {
                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    Toast.makeText(POIdetails_Activity.this, "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
                }
                if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
                    //起终点或途经点地址有岐义，通过以下接口获取建议查询信息
                    //result.getSuggestAddrInfo()
                    return;
                }
                if (result.error == SearchResult.ERRORNO.NO_ERROR) {
                    nodeIndex = -1;
                    route = result.getRouteLines().get(0);
                    DrivingRouteOverlay overlay = new MyDrivingRouteOverlay(mBaidumap);
                    routeOverlay = overlay;
                    mBaidumap.setOnMarkerClickListener(overlay);
                    overlay.setData(result.getRouteLines().get(0));
                    overlay.addToMap();
                    overlay.zoomToSpan();
                }
            }
        });

        poidetails_name_TextView = (TextView) findViewById(R.id.poidetails_name_TextView);
        poidetails_address_TextView = (TextView) findViewById(R.id.poidetails_address_TextView);
        poidetails_phone_TextView = (TextView) findViewById(R.id.poidetails_phone_TextView);
        detail_distance_TextView = (TextView) findViewById(R.id.detail_distance_TextView);
        Intent intent = getIntent();
//        SharedPreferences sharedPreferences = getSharedPreferences("PoiDetails", MODE_PRIVATE);

        poidetails_name_TextView.setText(intent.getStringExtra("name"));

        poidetails_address_TextView.setText(intent.getStringExtra("address"));
        if (intent.getStringExtra("tel").equals("")) {
            poidetails_phone_TextView.setText("暂无数据");
        } else {
            poidetails_phone_TextView.setText(intent.getStringExtra("tel"));
        }



        detail_distance_TextView.setText("全程约" + intent.getStringExtra("distance") + "，耗时约15分钟");
        poi_details_back_bt = (Button) findViewById(R.id.poi_details_back_bt);
        poi_details_back_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        View Tab1 = LayoutInflater.from(this).inflate(R.layout.tabhost_tabwidget, null);
        TextView textView1 = (TextView) Tab1.findViewById(R.id.tabwidget_TextView);
        textView1.setText("步行");
        ImageView imageView1 = (ImageView) Tab1.findViewById(R.id.tabwidget_ImageView);
        imageView1.setImageResource(R.drawable.ic_byfoot);


        View Tab2 = LayoutInflater.from(this).inflate(R.layout.tabhost_tabwidget2, null);
        TextView textView2 = (TextView) Tab2.findViewById(R.id.tabwidget2_TextView);
        textView2.setText("公交");
//        ImageView imageView2 = (ImageView) Tab1.findViewById(R.id.tabwidget_ImageView);
//        imageView2.setImageResource(R.drawable.ic_byfoot);

        View Tab3 = LayoutInflater.from(this).inflate(R.layout.tabhost_tabwidget3, null);
        TextView textView3 = (TextView) Tab3.findViewById(R.id.tabwidget3_TextView);
        textView3.setText("驾车");
        ImageView imageView3 = (ImageView) Tab3.findViewById(R.id.tabwidget3_ImageView);
        imageView3.setImageResource(R.drawable.ic_bycar);


        tabhost = (TabHost) findViewById(R.id.tabhost);
        tabhost.setup();
        tabhost.addTab(tabhost.newTabSpec("TAB1")
//                .setIndicator("步行",getResources().getDrawable(R.drawable.ic_byfoot))
                .setIndicator(Tab1)
                .setContent(R.id.content1_LinearLayout));
        tabhost.addTab(tabhost.newTabSpec("TAB2")
                .setIndicator(Tab2)
                .setContent(R.id.content2_LinearLayout));
        tabhost.addTab(tabhost.newTabSpec("TAB3")
                .setIndicator(Tab3)
                .setContent(R.id.content3_LinearLayout));

        SharedPreferences preferences = getSharedPreferences("coordinate", MODE_PRIVATE);
        String loc = preferences.getString("coordinate", "");
        String st[] = loc.split(",");
        double from_x = Double.parseDouble(st[0]);
        double from_y = Double.parseDouble(st[1]);
        fromLatLng = new LatLng(from_y, from_x);
        double to_y = Double.parseDouble(intent.getStringExtra("y"));
        double to_x = Double.parseDouble(intent.getStringExtra("x"));
        toLatLng = new LatLng(to_y, to_x);
        final PlanNode stNode = PlanNode.withLocation(fromLatLng);
        final PlanNode enNode = PlanNode.withLocation(toLatLng);
        tabhost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
            @Override
            public void onTabChanged(String tabId) {
                route = null;
                mBaidumap.clear();
//                Toast.makeText(POIdetails_Activity.this, tabId, Toast.LENGTH_SHORT).show();
                if (tabId.equals("TAB1")) {
                    mSearch.walkingSearch((new WalkingRoutePlanOption())
                            .from(stNode)
                            .to(enNode));

                }
                if (tabId.equals("TAB2")) {
                    mSearch.transitSearch((new TransitRoutePlanOption())
                            .from(stNode)
                            .city("西安")
                            .to(enNode));
                }
                if (tabId.equals("TAB3")) {
                    mSearch.drivingSearch((new DrivingRoutePlanOption())
                            .from(stNode)
                            .to(enNode));
                }
            }
        });

        //定位图层
        mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
        mBaidumap
                .setMyLocationConfigeration(new MyLocationConfiguration(
                        mCurrentMode, true, mCurrentMarker));
        // 开启定位图层
        mBaidumap.setMyLocationEnabled(true);
        // 定位初始化
        locationClient = new LocationClient(this);
        locationClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// 打开gps
        option.setCoorType("gcj02"); // 设置坐标类型
        locationClient.setLocOption(option);
        locationClient.start();

        //默认步行
        mSearch.walkingSearch((new WalkingRoutePlanOption())
                .from(stNode)
                .to(enNode));
    }


    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null)
                return;
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                            // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaidumap.setMyLocationData(locData);
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
                mBaidumap.animateMapStatus(u);
            }
        }

        public void onReceivePoi(BDLocation poiLocation) {
        }
    }

    //定制RouteOverly
    private class MyDrivingRouteOverlay extends DrivingRouteOverlay {

        public MyDrivingRouteOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public BitmapDescriptor getStartMarker() {
            if (useDefaultIcon) {
                return BitmapDescriptorFactory.fromResource(R.drawable.ic_loc_from);
            }
            return null;
        }

        @Override
        public BitmapDescriptor getTerminalMarker() {
            if (useDefaultIcon) {
                return BitmapDescriptorFactory.fromResource(R.drawable.ic_loc_to);
            }
            return null;
        }
    }

    private class MyWalkingRouteOverlay extends WalkingRouteOverlay {

        public MyWalkingRouteOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public BitmapDescriptor getStartMarker() {
            if (useDefaultIcon) {
                return BitmapDescriptorFactory.fromResource(R.drawable.ic_loc_from);
            }
            return null;
        }

        @Override
        public BitmapDescriptor getTerminalMarker() {
            if (useDefaultIcon) {
                return BitmapDescriptorFactory.fromResource(R.drawable.ic_loc_to);
            }
            return null;
        }
    }

    private class MyTransitRouteOverlay extends TransitRouteOverlay {

        public MyTransitRouteOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public BitmapDescriptor getStartMarker() {
            if (useDefaultIcon) {
                return BitmapDescriptorFactory.fromResource(R.drawable.ic_loc_from);
            }
            return null;
        }

        @Override
        public BitmapDescriptor getTerminalMarker() {
            if (useDefaultIcon) {
                return BitmapDescriptorFactory.fromResource(R.drawable.ic_loc_to);
            }
            return null;
        }
    }

    //导航方法
    public void startWebNavi(LatLng pt1,LatLng pt2) {
        // 构建 导航参数
        NaviPara para = new NaviPara();
        para.startPoint = pt1;
        para.endPoint = pt2;
        BaiduMapNavigation.openWebBaiduMapNavi(para, this);
    }
}
